# -*- coding: utf-8 -*-
import scrapy
import base64
from urllib.parse import quote
from scrapy.utils.project import get_project_settings
from zc_core.model.items import Box
from zc_core.spiders.base import BaseSpider
from plap_zc.rules import *
from plap_zc.utils.login_selenium import SeleniumLogin


# Util.encrypt
class SupplierSpider(BaseSpider):
    name = 'supplier'
    customer = ''
    custom_settings = {
        'CONCURRENT_REQUESTS': 12,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 12,
        'CONCURRENT_REQUESTS_PER_IP': 12,
    }
    # 本地商品报价链接
    supplier_list_url1 = 'https://zc.plap.mil.cn/EpointMallService/rest/basicinfo_spgys/searchgys'

    def __init__(self, customer=None, batchNo=None, *args, **kwargs):
        settings = get_project_settings()
        self.customer = customer
        if not customer:
            self.customer = settings.get('CUSTOMER', None)
        super(SupplierSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        if not self.customer:
            raise Exception('请指定客户')
        self.size = 8
        self.cookie_dict = SeleniumLogin().get_cookies(self.customer)

    def _build_supplier(self, page):
        return scrapy.FormRequest(
            url=self.supplier_list_url1,
            method='POST',
            meta={
                'batchNo': self.batch_no,
                'page': page,
            },
            headers={
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
                "Connection": "keep-alive",
                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                "Host": "zc.plap.mil.cn",
                "Origin": "https://zc.plap.mil.cn",
                "Referer": "https://zc.plap.mil.cn/localprice.html?version=1001",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84",
                "X-Requested-With": "XMLHttpRequest",
            },
            formdata={"frameBodySecretParam": str(
                quote(str(base64.b64encode(quote(json.dumps(
                    {"gysName": "", "currentPageIndex": "{}".format(page), "pageSize": 8, "sort": "",
                     "url": "https://zc.plap.mil.cn/gyssearch.html", "referer": "https://zc.plap.mil.cn/gyssearch.html"
                     })).replace('%20', '').replace('/', '%2F').encode(
                    'utf-8')))[2:-1]).replace('%20', '').replace('/',
                                                                 '%2F'))},
            # formdata={"frameBodySecretParam":"JTdCJTIyY2lkJTIyJTNBJTIyJTIyJTJDJTIyeGRwcm9kdWN0Y29kZSUyMiUzQSUyMiUyMiUyQyUyMnByb2R1Y3RuYW1lJTIyJTNBJTIyJTIyJTJDJTIyYnJhbmRuYW1lJTIyJTNBJTIyJTIyJTJDJTIyc3RhdHVzJTIyJTNBJTIyMCUyMiUyQyUyMmlzdHVpamlhbiUyMiUzQSUyMiUyMiUyQyUyMnBhZ2UlMjIlM0ExJTJDJTIyc2l6ZSUyMiUzQTEwJTJDJTIycmVmZXJlciUyMiUzQSUyMmh0dHBzJTNBJTJGJTJGemMucGxhcC5taWwuY24lMkZsb2NhbHByaWNlLmh0bWwlMjIlN0Q%3D"},
            callback=self.parse_supplier,
            errback=self.error_back,
            cookies=self.cookie_dict,
            priority=200,
        )

    def start_requests(self):
        yield self._build_supplier(1)

    # 处理supplier列表
    def parse_supplier(self, response):
        meta = response.meta
        curr_page = meta.get('page')
        supplier_list = parse_supplier(response)
        if curr_page == 1:
            for page in range(2, parse_supplier_page(response, self.size) + 1):
                yield self._build_supplier(page)
        else:
            yield Box('supplier', self.batch_no, supplier_list)
